package com.bbjob.util;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;


public class QRCode {
	

	public static ByteArrayOutputStream getQRCode(String text) throws Exception {
		return getQRCode(text,null);
	}
	
	public static ByteArrayOutputStream getQRCode(String text,String logoPath) throws Exception {
		ByteArrayOutputStream os= new ByteArrayOutputStream();
		MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
		Map<EncodeHintType, String> hints = new HashMap<EncodeHintType, String>();
		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");// 这个utf8一定要小写
		BitMatrix bitMatrix = multiFormatWriter.encode(text,
				BarcodeFormat.QR_CODE, 167, 167, hints);
		
		writeToStream(bitMatrix, "jpg", os, logoPath);
		return os;
	}
	public static void writeToStream(BitMatrix matrix, String format,
			OutputStream stream, String logoPath) throws IOException {
		BufferedImage image = toBufferedImage(matrix);
		if (null != logoPath) {
			File logo = new File(logoPath);
			if (logo.exists() && logo.isFile()) {
				Graphics2D gs = image.createGraphics();
				// 载入logo
				Image img = ImageIO.read(new File(logoPath));
				int wah = matrix.getHeight();
				int x = (wah - 25) / 2;
				gs.drawImage(img, x, x, 25, 25, null);
				gs.dispose();
				img.flush();
			}
		}
		if (!ImageIO.write(image, format, stream)) {
			throw new IOException("Could not write an image of format "
					+ format);
		}
	}

	public static BufferedImage toBufferedImage(BitMatrix matrix) {
		int width = matrix.getWidth();
		int height = matrix.getHeight();
		BufferedImage image = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		for (int x = 0; x < width; x++) {
			for (int y = 0; y < height; y++) {
				image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
			}
		}
		return image;
	}

	private static final int BLACK = 0xFF000000;
	private static final int WHITE = 0xFFFFFFFF;

	
}
